#include "InputManager.h"

using namespace sf;

InputManager::InputManager(RenderWindow* window, Player* player):
window(window),
player(player),
collisionManager(CollisionManager::getInstance())
{
}

InputManager::~InputManager(void)
{
}

void InputManager::processInput(float elapsedTime)
{
	const Input& input = window->GetInput();
	b2Shape* playerShape = player->getBody()->GetShapeList();
	bool onGround = collisionManager->isOnGround(playerShape);
	bool onWall = collisionManager->isOnWall(playerShape);

	//Reset
	if (input.IsKeyDown(Key::R)) {
		player->getBody()->SetLinearVelocity(b2Vec2_zero);
		player->getBody()->SetXForm(b2Vec2(0.0f, 0.0f), 0.0f);
	}

	//Player input
	if (onGround || !onWall) {
		if (input.IsKeyDown(Key::Right)) {
			float impulse = (player->getMaxWalkVelocity() - player->getBody()->GetLinearVelocity().x) / 12.0f;
			player->getBody()->ApplyImpulse(b2Vec2(impulse, 0), player->getBody()->GetWorldCenter());
			player->getSprite()->FlipX(false);
		}
		if (input.IsKeyDown(Key::Left)) {
			float impulse = -(player->getMaxWalkVelocity() + player->getBody()->GetLinearVelocity().x) / 12.0f;
			player->getBody()->ApplyImpulse(b2Vec2(impulse, 0), player->getBody()->GetWorldCenter());
			player->getSprite()->FlipX(true);
		}
	}
	if (input.IsKeyDown(Key::Up)) {
		player->getBody()->ApplyImpulse(b2Vec2(0, (player->getJumpVelocity() - player->getBody()->GetLinearVelocity().y) * elapsedTime * 10.0f), player->getBody()->GetWorldCenter());
	}
	if (input.IsKeyDown(Key::Down)) {
		player->getBody()->ApplyImpulse(b2Vec2(-player->getBody()->GetLinearVelocity().x, 0), player->getBody()->GetWorldCenter());
	}
	if (onGround && input.IsKeyDown(Key::Space)) {
		player->getBody()->ApplyImpulse(b2Vec2(0, 5.0f), player->getBody()->GetWorldCenter());
	}
	if (!onGround) {
		player->getBody()->ApplyForce(b2Vec2(-1.6f * player->getBody()->GetLinearVelocity().x, 0), player->getBody()->GetWorldCenter());
	}

	if (onGround) {
		if (input.IsKeyDown(Key::Right) || input.IsKeyDown(Key::Left)) {
			player->getSprite()->setAnimation("walk");
		} else {
			player->getSprite()->setAnimation("idle");
		}
	} else {
		player->getSprite()->setAnimation("jump");
	}

	/*
	//Zoom
	if (input.IsKeyDown(Key::I)) {
		zoom += elapsedTime;
		scrollView.Zoom(1.0f + elapsedTime);
	}
	if (input.IsKeyDown(Key::O)) {
		zoom -= elapsedTime;
		scrollView.Zoom(1.0f - elapsedTime);
	}
	if (input.IsKeyDown(Key::P)) {
		scrollView.Zoom(1/zoom);
		zoom = 1.0f;
	}
	*/
}
